package com.im.project.rabbitmq;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.im.common.constant.Constant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * mq消息生产
 *
 * @author yunZhouJiaDi
 */
@Slf4j
@Component
public class RabbitmqProducer<T> implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnsCallback {

    private static RabbitTemplate rabbitTemplate;

    @Autowired
    public RabbitmqProducer(RabbitTemplate rabbitTemplate) {
        RabbitmqProducer.rabbitTemplate = rabbitTemplate;
    }

    public void sendMessageProducer(String routingKey, T data) {
        rabbitTemplate.setMandatory(true);
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnsCallback(this);
        CorrelationData correlationData = new CorrelationData("id_" + UUID.randomUUID().toString());
        JSONObject jsonObject = (JSONObject) JSON.toJSON(data);
        Message msg = MessageBuilder.withBody(jsonObject.toJSONString().getBytes()).setMessageId(UUID.randomUUID().toString()).build();
        rabbitTemplate.convertAndSend(Constant.RabbitmqConstant.EXCHANGE_MESSAGE, routingKey, msg,
                message -> {
                    message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
                    return message;
                }, correlationData);
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        if (!ack) {
            log.error("消息ID=" + correlationData.getId() + "投递失败，失败原因：" + cause);
        } else {
            log.info("消息投递收到确认：correlationData=" + correlationData.getId());
        }
    }

    @Override
    public void returnedMessage(ReturnedMessage returnedMessage) {
        log.info("返回结果：" + JSONUtil.toJsonStr(returnedMessage));
    }
}
